<?php

	namespace nz\co\gravitate\FTAWebServices;

	require_once("fta.201003310000/fta.php");
	fta_registerModules(
		array(
		"FTAWebServices/FTASoapClient"
		)
	);
	
	define('FTA_DOTNET_SOAP_NAMESPACE','http://schemas.xmlsoap.org/soap/envelope/');

	/**
	* This class is a simple interface for performing soap rpc type method calls, it does not even try to understand wsdl. It implements basic namespacing and has been designed to ensure that it works with a .Net server
	*/
	class FTADOTNETSOAPClient extends FTASoapClient {

		public function __construct($host, $port=80, $endPoint, $proxy=null, $proxyPort = '8888') {
			parent::__construct ($host, $port, $endPoint, $proxy, $proxyPort);
		}	
		
		/**
		* prepares the xml payload for delivery to the server
		*/
		function payloadForInvocationWithNameAndArguments($methodName, $params) {
			// we take the method name.. and then read the args from the function argc/v 
			//$argv = func_get_args();
			//$argc = count($argv);

			$arguments = $this->getArgumentList($params);
			// here we take the arguments and just make sure all the types are correct.
			// this is a hangover from older code, but means that types
			// can be set/coreced when we get to encoding time.

			$head = $this->getHeaderForMethod($methodName);//new FTASimpleSoapHeader();
			$invocation = $this->getInvocationForMethodAndArguments($methodName,$arguments);
			
			//factor me out..
			$body = new FTASOAPBody($invocation,'soap');
		
			$payload = new FTASOAPEnvelope(
				$head,
				$body,
				'soap',
				array(
					'xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
					'xsd'=>'http://www.w3.org/2001/XMLSchema',
					'soap' => 'http://schemas.xmlsoap.org/soap/envelope/'
				)
			);
			return $payload;				

		}

		function processResponseStringForInvocation(FTASOAPInvocation $invocation, $string){
			$x = simplexml_load_string($string,"SimpleXMLElement",0,FTA_DOTNET_SOAP_NAMESPACE);// we need to add a name space here. so that we can get the right elements..
			if (is_null($x)){
				//throw an error here..
				throw new InvalidServerResponse("There was an error in the xml response",$string,array());				 
			}

			$this->lastResponse = $x;
						
			$faults = $x->Body->xpath('soap:Fault');
			if (is_array($faults) && count($faults) > 0) {
				// now.. we need to nest these bastards???				
				array_walk(
					$faults,
					function ($i){
						$f =  new FTASoapFault(); 
						$f->code =$i->faultcode . "";
						$f->message = $i->faultstring ."";
						$f->detail = $i->detail . "";
					}
				);				
				throw new SoapFaultException("A fault occured on the remote server", $string, $faults, array());
			}
			
			// hook in to the response here and 
			$response = $x->Body->children($invocation->ns)->{ $invocation->name . "Response"};			
			if (is_null($response))
				return null;
			
			return ($response->{  $invocation->name . "Result"});

		}
	
	
	
	}
